<template>
  <button
    id="backToTop"
    class="fixed bottom-6 right-6 w-12 h-12 bg-primary text-white rounded-full shadow-lg flex items-center justify-center opacity-0 invisible transition-all duration-300 hover:bg-primary/90 transform hover:scale-110 z-50"
    @click="scrollToTop"
  >
    <i class="fa fa-chevron-up"></i>
  </button>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'

// 平滑滚动到顶部
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth',
  })
}

// 监听滚动显示/隐藏按钮
const handleScroll = () => {
  const backToTopBtn = document.getElementById('backToTop')
  if (backToTopBtn) {
    if (window.scrollY > 300) {
      backToTopBtn.classList.remove('opacity-0', 'invisible')
      backToTopBtn.classList.add('opacity-100', 'visible')
    } else {
      backToTopBtn.classList.add('opacity-0', 'invisible')
      backToTopBtn.classList.remove('opacity-100', 'visible')
    }
  }
}

// 生命周期钩子
onMounted(() => {
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
/* 按钮动画已在模板的class中定义 */
</style>
